package cn.wh.beans.factory.support;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.OptionalBean;
import cn.wh.beans.BeansException;
import cn.wh.beans.PropertyValue;
import cn.wh.beans.PropertyValues;
import cn.wh.beans.factory.config.BeanDefinition;
import cn.wh.beans.factory.config.BeanReference;

import java.lang.reflect.Constructor;

/**
 * @Author wanghao
 * @Date 2022-08-21 1:19
 * @Description: bean的实例化 属性填充
 */
public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory {
    InstantiationStrategy strategy = new CglibSubclassingInstantiationStrategy();

    @Override
    protected Object createBean(BeanDefinition beanDefinition, String beanName, Object... args) {
        Object bean = null;
        //创建bean
        try {
            bean = doCreateBean(beanDefinition, beanName, args);
            //填充bean
            applyPropertyValues(beanName, bean, beanDefinition);
        } catch (BeansException e) {

        }
        //注册到单例容器
        addSingletonBean(beanName, bean);
        return bean;
    }

    private Object doCreateBean(BeanDefinition beanDefinition, String beanName, Object... args) throws BeansException {
        //获取ctor
        Constructor constructorUse = null;
        Constructor[] declaredConstructors = beanDefinition.getBeanClass().getDeclaredConstructors();
        for (Constructor declaredConstructor : declaredConstructors) {
            if (args != null && declaredConstructor.getParameterTypes().length == args.length) {
                constructorUse = declaredConstructor;
                break;
            }
        }
        return strategy.instantiate(beanDefinition, beanName, constructorUse, args);
    }

    private void applyPropertyValues(String beanName, Object bean, BeanDefinition beanDefinition) {
        PropertyValues propertyValues = beanDefinition.getPropertyValues();
        try {
            for (PropertyValue propertyValue : propertyValues.getPropertyValues()) {
                String name = propertyValue.getName();
                Object value = propertyValue.getValue();
                if (value instanceof BeanReference) {
                    BeanReference beanReference = (BeanReference) value;
                    value = getBean(beanReference.getBeanName());
                }
                BeanUtil.setProperty(bean, name, value);
            }
        } catch (Exception e) {
            throw new BeansException("实例化失败" + beanName);
        }
    }

    public InstantiationStrategy getStrategy() {
        return strategy;
    }

    public void setStrategy(InstantiationStrategy strategy) {
        this.strategy = strategy;
    }
}
